""" positions.py

This module provides the position handler class.

   Copyright 2011 Bravo369.org

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

author = Mike Meade (mmeade@google.com)
"""

# General imports
import handlers
import logging
import random
import string
import time

# Application imports
from data import position
from utils import html_utils

# Framework imports
from google.appengine.ext import db
from django.utils import simplejson as json


class Positions(handlers.Handler):
  """A convenience class to interact with a list of positions."""

  @classmethod
  def postPositions(cls, requestHandler):
    """Post the indicated positions.

    Args:
      requestHandler: The current requestHandler.request handler instance.
    """
    positions = json.loads(requestHandler.request.body)
    for position in positions:
      try:
        position.Position.fromDict(position['Position']).put()
      except Exception, e:
        logging.error(str(e))
        raise e

  @classmethod
  def deletePositions(cls, requestHandler):
    """Delete the indicated positions.

    Args:
      requestHandler: The current requestHandler.request instance.
    """
    query = html_utils.getAllQueries(requestHandler.request.query_string)
    if not 'session' in query:
      raise Exception()
    while True:
      positions = cls.filter(
          position.Position.all(),
          {'session =': query['session']}
          )

      if not positions:
        break
      for position in positions:
        position.delete()

  @classmethod
  def getPositions(cls,requestHandler):
    """Get the indicated positions.

    Args:
      requestHandler: The current requestHandler.request instance.
    """
    query = html_utils.getAllQueries(requestHandler.request.query_string)
    if not 'session' in query:
      raise Exception()
    instance = cls(requestHandler.request, requestHandler.requestHandler.response, query)
    try:
      if query.get('start_time', False):
        instance.returnIndicatedPositions()
      else:
        instance.returnAllPositions()
    except Exception, e:
      logging.error(str(e))
      raise

  def returnAllPositions(self, session):
    """Return the positions for the indicated session.

    Args:
      requestHandler: The current requestHandler.request instance.
    """
    logging.info('Getting all positions for session: %s', session)
    results = self.filter(
        position.Position.all(),
        {'session =': session}
        )

    results = [result.toJson() for result in results]
    self.requestHandler.response.set_status(200)
    self.requestHandler.response.headers.add_header('content-type', 'application/json')
    self.requestHandler.response.out.write(json.dumps(results, indent=2))

  def returnIndicatedPositions(self, session, start_time):
    """Return the indicated positions of the session.

    Args:
      session: The session to get the positions for.
      start_time: The earliest start time to use.
    """
    logging.info('Getting indicated positions for session: %s', session)
    filters = {
        'session =': session,
        'timestamp >': int(start_time)
        }

    results = self.filter(
        position.Position.all(), filters,
        200,
        order='timestamp'
        )

    results = [result.toJson() for result in results]
    logging.info('Returning %s positions.', len(results))
    self.requestHandler.response.set_status(200)
    self.requestHandler.response.headers.add_header('content-type', 'application/json')
    self.requestHandler.response.out.write(json.dumps(results, indent=2))
